{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%sh\n",
    "pip install -U pip\n",
    "pip install -qU yfinance openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import pprint\n",
    "\n",
    "import yfinance\n",
    "from api_key import api_key\n",
    "from IPython.display import Markdown, clear_output, display\n",
    "from openai import OpenAI\n",
    "\n",
    "endpoint = \"https://conductor.arcee.ai/v1\"\n",
    "\n",
    "client = OpenAI(\n",
    "    base_url=endpoint,\n",
    "    api_key=api_key,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_stock_price(company_name, stock_symbol):\n",
    "    stock = yfinance.Ticker(stock_symbol)\n",
    "    price = stock.history(period=\"1d\")[\"Close\"].values[0]\n",
    "    return (\n",
    "        f\"The last closing price of {company_name} ({stock_symbol}) was ${price:.2f}.\"\n",
    "    )\n",
    "\n",
    "\n",
    "def get_ceo_name(company_name, stock_symbol):\n",
    "    stock = yfinance.Ticker(stock_symbol)\n",
    "    info = stock.info\n",
    "    ceo = info[\"companyOfficers\"][0][\"name\"]\n",
    "    return f\"The CEO of {company_name} is {ceo}. The full job title is {info['companyOfficers'][0]['title']}.\"\n",
    "\n",
    "\n",
    "def get_company_summary(company_name, stock_symbol):\n",
    "    stock = yfinance.Ticker(stock_symbol)\n",
    "    summary = stock.info[\"longBusinessSummary\"]\n",
    "    return summary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "get_stock_price(\"Amazon\", \"AMZN\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "get_ceo_name(\"Ford\", \"F\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "get_company_summary(\"Verizon\", \"VZ\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "tools = [\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"get_stock_price\",\n",
    "            \"description\": \"\"\"Retrieves the most recent closing stock price that can answer questions about:\n",
    "- Current stock price\n",
    "- Recent stock performance\n",
    "- Company market value\n",
    "- Share price information\n",
    "\n",
    "Use this function for questions like:\n",
    "- \"What's the stock price of [company]?\"\n",
    "- \"How much does [company] stock cost?\"\n",
    "- \"What's [company]'s current share price?\"\n",
    "- \"How much are shares of [company] trading for?\"\n",
    "- \"What's the latest price for [stock symbol]?\"\n",
    "\"\"\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"company_name\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"The full company name (e.g., 'Apple Inc.', 'Tesla, Inc.', 'McDonald's Corporation')\",\n",
    "                    },\n",
    "                    \"stock_symbol\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"The stock market ticker symbol (e.g., 'AAPL', 'TSLA', 'MCD')\",\n",
    "                    },\n",
    "                },\n",
    "                \"required\": [\"company_name\", \"stock_symbol\"],\n",
    "            },\n",
    "        },\n",
    "    },\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"get_ceo_name\",\n",
    "            \"description\": \"\"\"Retrieves current leadership information that can answer questions about:\n",
    "- CEO name and title\n",
    "- Top executive information\n",
    "- Company leadership\n",
    "- Management details\n",
    "\n",
    "Use this function for questions like:\n",
    "- \"Who is the CEO of [company]?\"\n",
    "- \"Who runs [company]?\"\n",
    "- \"What's the name of [company]'s chief executive?\"\n",
    "- \"Who is in charge of [company]?\"\n",
    "- \"Who is [company]'s leader?\"\n",
    "\"\"\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"company_name\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"The full company name (e.g., 'Microsoft Corporation', 'Meta Platforms, Inc.', 'Ford Motor Company')\",\n",
    "                    },\n",
    "                    \"stock_symbol\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"The stock market ticker symbol (e.g., 'MSFT', 'META', 'F')\",\n",
    "                    },\n",
    "                },\n",
    "                \"required\": [\"company_name\", \"stock_symbol\"],\n",
    "            },\n",
    "        },\n",
    "    },\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"get_company_summary\",\n",
    "            \"description\": \"\"\"Retrieves a detailed business summary that can answer questions about:\n",
    "- Products and services offered\n",
    "- Target markets and industries served\n",
    "- Manufacturing and production capabilities\n",
    "- Business divisions and segments\n",
    "- Geographic operations\n",
    "- Company history and background\n",
    "- Competitive position\n",
    "- Core business activities\n",
    "\n",
    "Use this function for questions like:\n",
    "- \"Does [company] make [product]?\"\n",
    "- \"What industries does [company] serve?\"\n",
    "- \"What are [company]'s main products?\"\n",
    "- \"Does [company] operate in [industry/market]?\"\n",
    "- \"What does [company] do?\"\n",
    "- \"Tell me about [company]'s business\"\n",
    "- \"What kind of company is [company]?\"\n",
    "\"\"\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"company_name\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"The full company name (e.g., '3M Company', 'Johnson & Johnson', 'The Coca-Cola Company')\",\n",
    "                    },\n",
    "                    \"stock_symbol\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"The stock market ticker symbol (e.g., 'MMM', 'JNJ', 'KO')\",\n",
    "                    },\n",
    "                },\n",
    "                \"required\": [\"company_name\", \"stock_symbol\"],\n",
    "            },\n",
    "        },\n",
    "    },\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "def call_tools(user_prompt, max_tokens=128):\n",
    "    response = client.chat.completions.create(\n",
    "        model=\"auto-tool\",\n",
    "        messages=[{\"role\": \"user\", \"content\": user_prompt}],\n",
    "        tools=tools,\n",
    "        tool_choice=\"auto\",\n",
    "        max_tokens=max_tokens,\n",
    "    )\n",
    "\n",
    "    # Extract and print the model name from the response\n",
    "    model_name = response.model\n",
    "    print(f\"Model used: {model_name}\")\n",
    "\n",
    "    tool_calls = response.choices[0].message.tool_calls\n",
    "    results = []\n",
    "\n",
    "    # Check if there are any tool calls\n",
    "    if tool_calls:\n",
    "        for tool_call in tool_calls:\n",
    "            # Extract function name and arguments\n",
    "            function_name = tool_call.function.name\n",
    "            arguments_json = tool_call.function.arguments\n",
    "            arguments_dict = json.loads(arguments_json)\n",
    "\n",
    "            if function_name in globals():\n",
    "                # Get the function object based on its name\n",
    "                function_to_call = globals()[function_name]\n",
    "\n",
    "                print(f\"Calling {function_name} with arguments: {arguments_dict}\")\n",
    "\n",
    "                # Call the function with unpacked keyword arguments\n",
    "                result = function_to_call(**arguments_dict)\n",
    "                results.append(result)\n",
    "            else:\n",
    "                print(f\"Function {function_name} not found in the global namespace.\")\n",
    "                results.append(None)\n",
    "\n",
    "        return results\n",
    "    else:\n",
    "        # No tool call: print the generated response\n",
    "        print(\"No tool call\")\n",
    "        return None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def call_tools_and_invoke_model(model, user_prompt, max_tokens=1024):\n",
    "    tool_results = call_tools(user_prompt)\n",
    "\n",
    "    # Convert list of results to string if we got multiple results\n",
    "    tool_results_str = (\n",
    "        \"\\n\".join(tool_results) if isinstance(tool_results, list) else tool_results\n",
    "    )\n",
    "\n",
    "    response = client.chat.completions.create(\n",
    "        model=model,\n",
    "        messages=[\n",
    "            {\n",
    "                \"role\": \"system\",\n",
    "                \"content\": \"\"\"You are an expert financial and business analyst providing precise, well-researched answers.\n",
    "\n",
    "Your capabilities:\n",
    "- Analyze company information, financials, and market data\n",
    "- Compare companies and their products/services\n",
    "- Provide insights about business strategies and market positions\n",
    "- Explain industry trends and competitive dynamics\n",
    "\n",
    "Guidelines:\n",
    "1. Always start with analyzing the tool result if available\n",
    "2. Structure your response clearly using markdown\n",
    "3. Be detailed and thorough\n",
    "4. Include relevant context from your knowledge\n",
    "5. Support claims with data and sources when possible\n",
    "6. Stay neutral and objective\n",
    "\n",
    "Required sections:\n",
    "* Tool information - Did you use the tool or not?\n",
    "* Direct Answer - Address the main question first.\n",
    "* Analysis - Provide context and deeper insights\n",
    "* Resources - if applicable, include for all companies:\n",
    "   - Top-level company website\n",
    "   - Yahoo Finance page (if the company is listed)\n",
    "   - URL for company SEC filings (if the company is publicly traded)\n",
    "   - URL for Google search based on the user question\n",
    "\n",
    "If the tool result is unavailable or insufficient, acknowledge this first and proceed with your best analysis based on available knowledge.\"\"\",\n",
    "            },\n",
    "            {\n",
    "                \"role\": \"user\",\n",
    "                \"content\": f\"\"\"\n",
    "                    question: {user_prompt}\n",
    "                    tool results: {tool_results_str}\n",
    "                \"\"\",\n",
    "            },\n",
    "        ],\n",
    "        max_tokens=max_tokens,\n",
    "        stream=True,\n",
    "    )\n",
    "    return response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def print_streaming_response(response):\n",
    "    num_tokens = 0\n",
    "    content = \"\"\n",
    "    for message in response:\n",
    "        if len(message.choices) > 0:\n",
    "            num_tokens += 1\n",
    "            chunk = message.choices[0].delta.content\n",
    "            if chunk:\n",
    "                content += chunk\n",
    "                clear_output(wait=True)\n",
    "                display(Markdown(content))\n",
    "\n",
    "    print(f\"\\n\\nNumber of tokens: {num_tokens}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "#user_prompt = \"Who's the CEO of General Motors?\"\n",
    "#user_prompt = \"What's the last price of Mc Donalds?\"\n",
    "user_prompt = \"Does 3M make filtration products for the automotive industry?\"\n",
    "#user_prompt = \"On which products do Procter and Gamble and Johnson & Johnson compete the most?\"\n",
    "# user_prompt = \"What's the population of the capital of New Zealand?\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "response = call_tools(user_prompt)\n",
    "pprint.pprint(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "response = call_tools_and_invoke_model(model=\"blitz\", user_prompt=user_prompt)\n",
    "print_streaming_response(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "response = call_tools_and_invoke_model(model=\"virtuoso-large\", user_prompt=user_prompt)\n",
    "print_streaming_response(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
